package com.beone.admin.controller.app.common;

import com.alibaba.fastjson.JSONObject;
import com.base.common.beans.Result;
import org.springframework.stereotype.Controller;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * app基础控制器
 * </p>
 *
 * @author Pagenny
 * @date 2019-05-19 16:00
 **/
@Controller
public class BaseAppController {

    /**
     * 获取用户ID
     *
     * @return
     */
    protected Integer getUserId() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        // 在登录拦截器中已设置userId属性
        String userId = (String) request.getAttribute("userId");
        return Integer.valueOf(userId);
    }

    /**
     * 为了返回统一的结果...
     * @param jsonObject
     * @return
     */
    protected Result covertResult(JSONObject jsonObject) {
        try {
            if ("success".equals(jsonObject.getString("code"))) {
                return Result.success(jsonObject.getString("msg"));
            } else {
                return Result.failure(jsonObject.getString("msg"));
            }
        } catch (Exception e) {
            return Result.failure("系统异常");
        }
    }
}
